package com.atguigu.lease.web.app.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private Client client;

    @Override
    public void getCode(String phone) {
        try {
            //1.生成code 和 key
            String code = VerifyCodeUtil.getVerifyCode(6);
            String key = RedisConstant.APP_LOGIN_PREFIX + phone;
            if(redisTemplate.hasKey(key)){
                //用户已经发送了短信  等待验证即可
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
            //为了省钱 将时间写的长一点
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(phone);
            sendSmsRequest.setSignName("阿里云短信测试");
            sendSmsRequest.setTemplateCode("SMS_154950909");
            String param = """
                        {"code":"%s"}
                        """.formatted(code);
            sendSmsRequest.setTemplateParam(param);
            client.sendSms(sendSmsRequest);
            redisTemplate.opsForValue().set(key,code,60,TimeUnit.DAYS);
            System.out.println(key);
            System.out.println(code);
        } catch (Exception e) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
    }

    @Override
    public String login(LoginVo loginVo) {
        //1.校验用户传递的数据是否有效
        if(!StringUtils.hasLength(loginVo.getPhone())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        if(!StringUtils.hasLength(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //2.判断redis中是否有值  准备key
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        if(!redisTemplate.hasKey(key)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        //3.判断验证码是否正确
        String code = redisTemplate.opsForValue().get(key);
        if(!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //4.获取用户信息  根据手机号获取数据 如果没有则新增用户.
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

        //5.如果是新用户则应该新增
        if(userInfo == null){
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setNickname("尚庭用户-"+loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setAvatarUrl("http://192.168.126.128:9000/mylease/title.jpg");
            userInfoMapper.insert(userInfo);
        }

        //6.判断用户是否正经
        if(userInfo.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        //之后将数据存放到threadLocal中
        String token = JwtUtil.createToken(userInfo.getId());
        return token;
    }
}
